<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Demo</title>
    <style>
        .roomList {
            display: inline;
            float: left;
            margin-top: 20px;
            margin-left: 20px;
        }

        .roomPanel {
            margin-top: 100px;
        }
        .scroll{
            display: block;
            overflow:auto;
        }
        #msgList{

            width:500px;
            height:300px;


        }
        #sysMsgList{
            width:900px;
            height:200px;

        }
    </style>
</head>
<body>
<div id="container">
    <span>nickname：</span><input type="text" v-model="nickname">
    <input type="button" v-on:click="login" value="login">

    <ul id="sysMsgList" class="scroll">
        <li v-for="msg in sysMsg">[<span style="color:red;">{{msg.name}}</span>]{{msg.content}}</li>
    </ul>


    <div id="createRoom">
        <input type="button" v-on:click="createRoom" value="createRoom">

        <span>房间ID：</span><input type="text" v-model="targetRoomId"><input type="button" v-on:click="joinRoom"
                                                                           value="Join">

    </div>

    <div>
        <hr/>
        <div v-for="room in rooms" class="roomList">
            <input type="button" v-on:click="enterRoom(room.ID,room.RoomName)" id=“{{room.ID}}”
                   value="{{room.RoomName}}">
        </div>
    </div>

    <div id="main" class="roomPanel">
        <span>房间名：{{currentRoomName}}</span>
        <br/>
        <span>房间ID：{{currentRoomId}}</span>

        <hr/>
        <ul id="msgList" class="scroll">
            <li v-for="msg in messages">[<span style="color:red;">{{msg.name}}</span>]{{msg.content}}</li>
        </ul>
        <div class="controls">
            <input type="text" v-model="nickname">
            <input type="text" v-model="inputMessage">
            <input type="button" v-on:click="sendMessage" value="Send">
        </div>

    </div>
</div>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="../protos/common.js"></script>
<script src="../lib/vue.min.js" type="text/javascript"></script>
<!--[starx websocket library](https://github.com/topfreegames/pitaya-client-websocket)-->
<script src="../lib/protocol.js" type="text/javascript"></script>
<script src="../lib/wsclient.js" type="text/javascript"></script>
<script>

    $("#main").css("display", "none")

    $("#createRoom").css("display", "none")

    window["cc"] = {
        log: console.log,
        roomProto: proto,
        newEncode: function (route, data) {

            let buf;

            if (route === "room.backend.enter") {
                let pkg = new proto.protos.EnterRoomReq();

                pkg.setRoomid(data.roomId);
                pkg.setUsername(data.nickname);
                buf = pkg.serializeBinary();
            } else if (route === "room.backend.message") {
                let pkg = new proto.protos.SendMessageToRoomReq();
                pkg.setRoomid(data.roomId);
                pkg.setContent(data.content);
                buf = pkg.serializeBinary();
            }else if(route === "chatroom.connector.login"){
                let pkg = new proto.protos.Login()
                pkg.setNickname(data.nickname)
                buf = pkg.serializeBinary();
            }
            else {
                data = JSON.stringify(data);
                buf = Protocol.Package.strEncode(data);

            }
            return buf;

        },
    };

    var v = new Vue({
        el: "#container",
        data: {
            nickname: 'guest' + Date.now(),
            inputMessage: '',
            currentRoomName: "",
            currentRoomId: "",
            messages: [],
            sysMsg: [],
            rooms: [],
            targetRoomId: ""
        },
        methods: {
            login: function () {
               // console.log("request login");
                cc.log(this.nickname)
                starx.request("chatroom.connector.login", {nickname:this.nickname}, login);
            },
            createRoom: function () {
               // console.log("create room");
                starx.request("room.backend.createroom", {}, createRoom)
            },
            sendMessage: function () {
                starx.request('room.backend.message', {
                    roomId: this.currentRoomId,
                    content: this.inputMessage
                }, sendMsg);
                this.inputMessage = '';
            },
            enterRoom: function (roomId, roomName) {

                v.sysMsg.push({name: 'system', content: `请求进入房间 房间ID：${roomId},房间名：${roomName}`});

                starx.request("room.backend.enter", {roomId, nickname: this.nickname}, enterRoom)
            },
            joinRoom: function () {
                v.sysMsg.push({name: 'system', content: `请求加入房间 房间ID：${this.targetRoomId}`});
                starx.request("room.backend.enter", {roomId: this.targetRoomId, nickname: this.nickname}, enterRoom)
            }
        }
    });

    let sysMsgPush = function(msg){
        v.sysMsg.push(msg);
        $(".scroll")[0].scrollTop = $(".scroll")[0].scrollHeight +40;

    }

    let msgPush = function(msg){
        v.messages.push(msg);
        $(".scroll")[1].scrollTop = $(".scroll")[1].scrollHeight +40;

    }

    let onMessage = function (msg) {
        cc.log("onMessage")
        let data = JSON.parse(msg.data)
        if(data.code === 200){
            msgPush({name:data.data.username,content:data.data.content})
        }

    };

    let login = function (data) {
        let rid = data.rid;

        let body = JSON.parse(data.data)
        if (body.code === 200) {
            $("#createRoom").css("display", "block")
            cc.log(body.data)
            sysMsgPush({name: 'system', content: body.data.Msg});

            if(body.data.RoomId){


                v.sysMsg.push({name: 'system', content: `已在房间请求加入房间 房间ID：${body.data.RoomId}`});
                starx.request("room.backend.enter", {roomId: body.data.RoomId, nickname:  body.data.NickName}, enterRoom)
            }
        }
    };

    let sendMsg = function (data) {
        //console.log("sendMsg data", data)
    }

    let createRoom = function (data) {

        let rid = data.rid;
        if(typeof data.data === "string"){
            sysMsgPush({name: 'system', content: data.data});
            return;
        }
        let body = JSON.parse(data.data)
        if (body.code === 200) {
            let roomName = body.data.RoomName;
            let roomId = body.data.ID;
            sysMsgPush({name: 'system', content: `房间名：${roomName} | 房间ID：${roomId}`});

            v.rooms.push(body.data)
        }
    }


    let enterRoom = function (data) {
        cc.log("enterRoom", data);
        let rid = data.rid;
        let body = JSON.parse(data.data)
        if (body.code === 200) {
            v.messages = [];
            let roomName = body.data.RoomName;
            let roomId =body.data.ID;
            v.currentRoomName = roomName;
            v.currentRoomId = roomId;

            sysMsgPush({name: 'system', content: `房间名：${roomName} | 房间ID：${roomId}`});
            $("#main").css("display", "block")
        }else{
            sysMsgPush({name: 'system', content: body.data});
        }
    }

    let onNewUser = function (msg) {
        cc.log("onNewUser")
        let data = JSON.parse(msg.data)
        if(data.code === 200){
            msgPush({name:"system",content:data.data})
        }
    };

    let onMembers = function (data) {
        console.log("onMembers", data);
        msgPush({name: 'system', content: "members: " + data.members});
    };

    let onLeaveUser = function (msg) {
        cc.log("onLeaveUser")
        let data = JSON.parse(msg.data)
        if(data.code === 200){

            msgPush({name:"system",content:data.data.content})
        }
    };


    starx.init({
        host: '127.0.0.1',
        port: 5555,
        path: '/',
        reconnect: true,
        decode: function (buf) {
            let bufferLen = buf.length;
            let offset = 0;
            let flag = buf[offset++]

            let isCompressRoute = (flag & 0x01) === 0x01;
            let type = flag >> 1 & 0x07;

            let isErrMsg = flag & 0x20;
            let id = 0;
            let route = "";
            if (Protocol.Message.msgHasId(type)) {
                for (let i = offset; i < buf.length; i++) {
                    let num = buf[i];
                    id += (num & 0x7F) << (7 * (i - offset));
                    if (num < 128) {
                        offset += i;
                        break;
                    }
                }
            }

            if (Protocol.Message.msgHasRoute(type)) {

                if (isCompressRoute) {
                    route = parseInt((buf[offset++] << 8) + buf[offset++]);
                } else {
                    let routeLen = parseInt(buf[offset++]);
                    if (routeLen) {
                        let routeBuf = new Uint8Array(routeLen);
                        Protocol.Package.copyArray(routeBuf, 0, buf, offset, routeLen);
                        route = Protocol.Package.strDecode(routeBuf);
                        offset += routeLen;
                    } else {
                        route = "";
                    }
                }
            }

            let dataLen = bufferLen - offset;

            let dataBuf = new Uint8Array(dataLen);

            Protocol.Package.copyArray(dataBuf, 0, buf, offset, dataLen);

            let data = proto.protos.requestRes.deserializeBinary(dataBuf).toObject()

            return {type, id, route, isErrMsg, body: data}
        }
    }, function () {
        console.log("initialized");
        starx.on('onMessage', onMessage)
        starx.on("onNewUser", onNewUser);
        starx.on("onMembers", onMembers);
        starx.on("onLeaveUser", onLeaveUser);

    })

</script>
</body>
</html>